<template>
  <div class="experiment-wrapper white-bg">
    <div class="header-bar">
      <div class="header-title">
        <div class="title-logo">
          <div class="logo-text">AI云实验</div>
        </div>
        <div class="title-line"></div>
        <template v-if="tags">
          <div class="tags" v-for="(item, index) in tags" :key="index">
            {{ item }}
          </div>
        </template>
        <div class="title-text">{{ title }}</div>
      </div>
      <header-center
        @change-direction="hooks.handleChangeDirection"
        @change-size="hooks.handleChangeSize"
        @change-history="hooks.handleChangeHistory"
      />
      <div class="header-btns">
        <div class="btns">
          <div class="flex" @click="handleToggleMore">
            <img
              src="@/assets/icon-more-cur.png"
              v-if="showMore"
              class="icons"
            />
            <img src="@/assets/icon-more.png" v-else class="icons" />
            <span class="text" :class="{ blue: showMore }">更多操作</span>
          </div>

          <div class="show-more-box" v-if="showMore">
            <div class="more-btns">
              <img src="@/assets/icon-zoom.png" class="more-icons" />

              <span class="text">放大观测区域</span>
            </div>

            <div class="more-btns">
              <img src="@/assets/icon-adjust.png" class="more-icons" />
              <span class="text">重新安装</span>
            </div>
            <div class="more-btns" @click="handleSave">
              <img src="@/assets/icon-save.png" class="more-icons" />
              <span class="text">保存实验</span>
            </div>
            <div class="more-btns" @click="handleOptionsTip">
              <img src="@/assets/icon-tip.png" class="more-icons" />

              <span class="text">操作提示</span>
            </div>
            <div class="more-btns" @click="outVisible = true">
              <img src="@/assets/icon-out.png" class="more-icons" />

              <span class="text">退出实验</span>
            </div>
          </div>
        </div>

        <!-- <div class="btn-line"></div>
        <div class="btns">
          <img src="@/assets/icon-record-cur.png" class="icons" />
          <span class="text">记录数据</span>
        </div> -->
        <div class="btn-line"></div>
        <div class="btns">
          <img src="@/assets/icon-time.png" class="icons" />

          <span class="text blue num">{{ realTime }}</span>
        </div>
        <div class="btn-line"></div>
        <div class="header-btn" @click="handleShare">分享</div>
        <div class="btn-line"></div>
        <div class="header-btn" @click="handleOver">实验完成</div>
      </div>
    </div>
    <div class="experiment-box">
      <!-- 左侧组件 -->
      <sider-step ref="stepRef" :datas="datas" />
      <!-- 右侧组件 -->
      <draw :is-show-mode="false" />
      <!-- 底部组件 -->
      <grid :is-show="showBootom" />
      <div class="experiment-main">
        <div class="main-box" ref="boxRef">
          <!-- 3d层 -->
          <div class="iframe-box">
            <div
              class="click-box"
              v-if="mockClickData.show"
              :style="{
                top: mockClickData.pos.y - 15 + 'px',
                left: mockClickData.pos.x - 15 + 'px',
              }"
            ></div>
            <iframe
              :src="iframeUrlNew"
              ref="iframeRef"
              class="iframe"
              @load="sendChangeStatus"
            ></iframe>
          </div>
        </div>
      </div>
      <!-- 操作提示弹窗 -->
      <start-tip
        :isShow="tipPoupShow"
        :datas="datas"
        @close-tip-poup="handleCloseTipPoup"
      ></start-tip>
      <!-- 完成实验提示组件 -->
      <end-tip :isShow="isShowOver" @to-report="handleToReport"></end-tip>
      <!-- 退出实验提示组件 -->
      <outTip
        :outVisible="outVisible"
        @handleSave="handleOutSave"
        @handleOut="handleOut"
        @handleCancel="outVisible = false"
      ></outTip>
    </div>
    <!-- 操作提示弹窗 -->
    <shareTip v-model:value="shareOpen"></shareTip>
    <!-- 轻量操作流程组件 -->
    <stepTip></stepTip>
    <!-- 自动操作流程组件 -->
    <autoTip></autoTip>
    <!-- 练习进入后的3d弹窗 -->
    <SavePoup></SavePoup>
  </div>
</template>
<script setup lang="ts">
import { ref, computed, onMounted, onUnmounted, reactive, watch } from "vue";
import { useRouter } from "vue-router";
//iframe地址
import { iframeUrl } from "@/utils/iframe";
import headerCenter from "@/components/standard/header-center.vue";
//左侧组件
import siderStep from "@/components/standard/sider-step.vue";
//右侧组件
import draw from "@/components/standard/draw/index.vue";
//底部组件
import grid from "@/components/standard/grid/index.vue";
//进入页面提示组件
import startTip from "@/components/standard/tip/startTip.vue";
//结束时提示组件
import endTip from "@/components/standard/tip/endTip.vue";
//分享弹窗组件
import shareTip from "@/components/shareTip/index.vue";
//轻量操作流程提示组件
import stepTip from "@/components/stepTip/index.vue";
//自动操作流程提示组件
import autoTip from "@/components/autoTip/index.vue";
//结束时提示组件
import outTip from "@/components/outTip/index.vue";
//3d弹窗
import SavePoup from "@/components/savePoup/index.vue";
import * as hooks from "@/hooks/useTestHooks";
import { useEventStore } from "@/store/modules/events";
import { message } from "ant-design-vue";
import API from "@/api/user";
import { useTipsStore } from "@/store/modules/tips";
const tipsStore = useTipsStore();
const store = useEventStore();
const iframeRef = hooks.useIframeRef();
const router = useRouter();
const query: any = computed(() => router.currentRoute.value.query);
//页面标题
const title: any = ref("");
//页面标签
const tags: any = ref([]);
//更新页面数据
const datas: any = ref({});
const getData = async () => {
  const res: any = await API.ExperimentFetchModel({
    experiment_id: query.value.id,
  });
  datas.value = res;
  title.value = res?.name;
};
const chooseFinifsh = computed(() => {
  return store.chooseFinifsh;
});

const showBootom: any = ref(false);
const saveData: any = ref();
//3diframe地址
const iframeUrlNew = computed(() => `${iframeUrl}&expid=${query.value.code}`);
const isCloseTip = ref(false); //轻量提示是否关闭
const isCloseAutoTip = ref(false); //自动提示是否关闭
const handleSendAuto = () => {
    tipsStore.setAutoTip(true);
    hooks.useHandleAutoTip();
};

//监听3d传过来的消息
const handleMessage = async (e: any) => {
  //console.log("接收iframe的消息：", e.data);
  if (e.data.type === "sendShowBootom") {
    showBootom.value = e.data;
  }
  if (e.data.type == "sendSaveData") {
    console.log("接收iframe的消息：", e.data);
    saveData.value = e.data.data.opRecordList;
    handleSaveData();
  }
  if (e.data.type == "sendStepTip") {
    console.log("接收iframe的消息：", e.data);
    hooks.useHandleSetStoreTip(e.data.data);
  }
  if (e.data.type == "sendChooseTip") {
    console.log("接收iframe的消息：", e.data);
    isCloseTip.value = true;
    tipsStore.setShowNotAutoTip(false);
  }
  //接收自动提示
  if (e.data.type == "sendStepAutoTip") {
    console.log("自动提示：", e.data);
    hooks.useHandleSetStoreAutoTip(e.data.data);
  }
  //关闭自动提示框的方法
  if (e.data.type == "sendCloseAutoTip") {
    isCloseAutoTip.value = true;
    //  if(e.data.data){
    //   console.log("111111111111111111111111自动退出实验");
    //   tipsStore.setIsExitSatus(true);
    // }
    tipsStore.setShowAutoTip(false);
  }
  if (e.data.type == "sendPlayTip") {
    store.setSavePoup(true);
    store.setSaveContent(e.data.data);
  }
  if (e.data.type == "sendClosePlayTip") {
    store.setSavePoup(false);
  }
  if (e.data.type === "mockclick") {
    //3d模拟点击事件发送过来的消息
    console.log("点击消息", e.data);
    handleSetMockClick(e.data.data);
  }
  if (e.data.type === "autoUiClick") {
    //web模拟点击事件发送过来的消息
    console.log("点击消息", e.data);
    if (e.data.data.para == "startMeasurement") {
      //模拟点击开始测量按钮事件
      hooks.useHandleStartMeasurement();
    }
    if (e.data.data.para == "changeOperate") {
      //模拟点击操作控制按钮事件
      hooks.useHandleChangeOperate(e.data.data.oppara, false);
    }
  }
};
const mockClickData = ref({
  show: false,
  pos: { x: 0, y: 0 },
});
const handleSetMockClick = (pos: any) => {
  mockClickData.value = {
    show: true,
    pos: pos,
  };
  setTimeout(() => {
    mockClickData.value = {
      show: false,
      pos: { x: 0, y: 0 },
    };
  }, 500);
};

const isSaveStatus = ref(false);
const handleSaveData = async () => {
  const params = {
    the_experiment_id: query.value.expuid,
    operation_json: JSON.stringify(saveData.value),
  };
  await API.StudentExperimentCreateStudentExperimentStep(params);
  console.log(111, isShare.value);
  isSaveStatus.value = false;
  message.success("保存成功");
  //分享
  if (isShare.value) {
    shareOpen.value = true;
  }
  //完成实验
  if (isFinishedStatus.value) {
    isShowOver.value = true;
  }
  //退出实验页面
  if(isOut.value){
    router.go(-2)
  }
};
const handleSave = () => {
  if (isSaveStatus.value) return;
  if (iframeRef.value?.contentWindow) {
    const datas = {
      type: "handleSave",
      data: query.value.expuid,
    };
    iframeRef.value.contentWindow.postMessage(datas, "*");
    isSaveStatus.value = true;
  }
};
const handleOptionsTip = () => {
  console.log("点击了操作提示");
  showMore.value = false;
  hooks.useHandleOptionsTip();
};
//更多操作按钮显示隐藏控制
const showMore = ref(false);
//更多操作按钮点击事件控制显示隐藏状态
const handleToggleMore = () => {
  showMore.value = !showMore.value;
};
//iframe加载完成发送消息给3d页面，open状态
const sendChangeStatus = () => {
  if (iframeRef.value?.contentWindow) {
    const datas = {
      type: "changeStatus",
      data: "open",
    };
    iframeRef.value.contentWindow.postMessage(datas, "*");
    setTimeout(() => {
      if (query.value.isSave) {
        getStudentStepDatas();
      }
    }, 1000);
  }
};
//实验时间
const realTime: any = ref("0:00");
//计时器
const timer = ref<number>();
//进入页面后的提示步骤弹窗
const tipPoupShow = ref(true);
//格式化时间
const formatTime = (elapsedSeconds: number) => {
  const minutes = Math.floor(elapsedSeconds / 60);
  const seconds = String(elapsedSeconds % 60).padStart(2, "0");
  return `${minutes}:${seconds}`;
};
//提示步骤弹窗关闭事件
const handleCloseTipPoup = () => {
  tipPoupShow.value = false;
  if(query.value.isFirst){
    handleSendAuto();
  }
 handleStartTime();
};
const handleStartTime = ()=>{
  clearInterval(timer.value);
  const startTime = Date.now();
  timer.value = setInterval(() => {
    const elapsedTime = Math.floor((Date.now() - startTime) / 1000);
    realTime.value = formatTime(elapsedTime);
  }, 1000);
}
//实验完成弹窗显示隐藏控制
const isShowOver = ref(false);
//实验完成按钮点击事件
const isFinishedStatus = ref(false);

const handleOver = () => {
  isFinishedStatus.value = true;
  //isShowOver.value = true;
  handleSave();
};
const isShare = ref(false);
const shareOpen = ref(false);
const handleShare = async () => {
  isShare.value = true;
  handleSave();
};
//实验完成弹窗关闭事件，跳转报告页面
const handleToReport = async () => {
  if (query.value.report_id) {
    router.push({
      path: "/report",
      query: {
        id: query.value.id,
        type: query.value.type,
        code: query.value.code,
        expuid: query.value.expuid,
        homework_id: query.value.homework_id,
        report_id: query.value.report_id,
      },
    });
  } else {
    let params = {
      student_experiment_id: query.value.expuid,
    };
    const res: any = await API.StudentExperimentFinishStudentExperiment(params);
    router.push({
      path: "/report",
      query: {
        id: query.value.id,
        type: query.value.type,
        code: query.value.code,
        expuid: query.value.expuid,
        homework_id: query.value.homework_id,
        report_id: res.report_id,
      },
    });
  }
};
const stepRef = ref();
const outVisible = ref(false);
const isOut = ref(false);
const handleOutSave = () => {
  isOut.value = true;
  handleSave();
};
const handleOut = () => {
  router.go(-2);
};
onMounted(() => {
  window.addEventListener("message", handleMessage);
  stepRef.value.handleChange(3);
  if (query.value.isSave) {
    tipPoupShow.value = false;
    handleStartTime();
  } else {
    tipPoupShow.value = true;
  }
  getData();
});
onUnmounted(() => {
  window.removeEventListener("message", handleMessage);
  clearInterval(timer.value);
});
watch(
  () => chooseFinifsh,
  (val) => {
    if (val) {
      if (iframeRef.value?.contentWindow) {
        const datas = {
          type: "changeChoose",
          data: "finifsh",
        };
        iframeRef.value.contentWindow.postMessage(datas, "*");
      }
    }
  },
  {
    immediate: true,
    deep: true,
  }
);
//监听是否关闭轻量提示框如果不是3d那边的消息让关闭提示框 给3d发送消息
watch(
  () => tipsStore.showNotAutoTip,
  (val) => {
    if (val == false && isCloseTip.value == false) {
      hooks.useHandleCloseTip();
    }
  },
  {
    immediate: true,
  }
);
//监听是否关闭自动提示框如果不是3d那边的消息让关闭提示框 给3d发送消息
watch(
  () => tipsStore.showAutoTip,
  (val) => {
    if (val == false && isCloseAutoTip.value == false) {
      hooks.useHandleCloseTip();
    }
  },
  {
    immediate: true,
  }
);
//监听是否跳过当前步骤 给3d发送消息

watch(
  () => tipsStore.isNext,
  (val) => {
    if (val == true) {
      hooks.useHandleSetNext();
    }
  },
  {
    immediate: true,
  }
);
//监听是否自动退出退出回到列表页面
watch(()=>tipsStore.isAutoExit,(val)=>{
  if(val==true){
    router.go(-2)
  }
},{
  immediate:true,

})
const sendData = ref();
const getStudentStepDatas = async () => {
  const res: any = await API.StudentExperimentStepsListForStudentExperiment({
    student_experiment_id: query.value.expuid,
  });
  console.log(res);
  if (res && res.length > 0) {
    sendData.value = JSON.parse(res[0].operation_json);
  }
  handleSendShare();
};
const handleSendShare = () => {
  if (!iframeRef.value?.contentWindow) return;
  if (!sendData.value) return;
  const params = {
    uid: query.value.expuid,
    opRecordList: JSON.parse(JSON.stringify(sendData.value)),
    type: "play", //type--share分享页面，type--play 继续练习使用
  };
  console.log("发送数据：", params);
  const message = {
    type: "sendShare",
    data: params,
  };

  iframeRef.value.contentWindow.postMessage(message, "*");
};
</script>
<style lang="less" scoped>
.experiment-wrapper {
  width: 100%;
  height: 100%;
  box-sizing: border-box;
}
.al-radius {
  position: fixed;
  right: 0px;
  top: 50%;
  cursor: pointer;
  z-index: 999;
  transform: translateY(-50%);
  width: 111px;
  height: 120px;
  background: url(@/assets/ai-radius.png) no-repeat center;
  background-size: 100%;
}
.tip-box-poup {
  width: 100%;
  height: 100%;
  position: fixed;
  top: 0;
  left: 0;
  z-index: 9999;
  .tip-bg {
    position: absolute;
    background: rgba(0, 0, 0, 0.4);
    left: 0;
    top: 0;
    width: 100%;
    height: 100%;
    z-index: 10000;
  }
  .tip-button {
    width: 437px;
    z-index: 10002;
    cursor: pointer;
    height: 59px;
    background: #2776ff;
    border-radius: 12px;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    bottom: 30px;
    left: 50%;
    transform: translateX(-50%);
    font-family: PingFangSC-Medium;
    font-weight: 500;
    font-size: 24px;
    color: #ffffff;
    line-height: 30px;
    img {
      width: 30px;
      height: 30px;
      margin-left: 10px;
    }
  }
  .tip-box-wrapper {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 10001;
    .tip-tab {
      width: auto;
      .tab-hd {
        height: 60px;
        display: flex;
        align-items: center;
        .hd-item {
          width: 162px;
          height: 60px;
          margin-right: 6px;
          background: #edf3fe;
          border-radius: 20px 20px 0 0;
          display: flex;
          align-items: center;
          justify-content: center;
          cursor: pointer;
          font-family: PingFangSC-Regular;
          font-weight: 400;
          font-size: 16px;
          color: #262626;
          text-align: center;

          &.cur {
            background: #2776ff;
            border: 1px solid #e6ebf1;
            border-radius: 0;
            color: #fff;
          }
        }
      }
      .tab-bd-box {
        width: 1081px;
        height: 485px;
        overflow-y: auto;
        background: #ffffff;
        border: 1px solid #e6ebf1;
        border-radius: 0 20px 20px 20px;
        .tab-bd {
          padding: 20px;
          display: flex;
          box-sizing: border-box;
          min-height: 100%;
          flex-direction: column;
          justify-content: center;
          .content-text {
            font-family: PingFangSC-Regular;
            font-weight: 400;
            font-size: 20px;
            color: #262626;
            letter-spacing: 0;
            line-height: 1.5;
            text-align: left;
          }
          .content-img {
            width: 50%;
            height: auto;
            margin: 20px auto;
            img {
              width: 100%;
            }
          }
        }
      }
    }
  }
}
.header-bar {
  display: flex;
  background: #fff;
  padding: 0 16px;
  height: 50px;
  position: relative;
  z-index: 99;
  justify-content: space-between;
  border-bottom: 1px solid #cecece;
  .header-title {
    display: flex;
    align-items: center;
    .title-logo {
      display: flex;
      align-items: center;
      .login-text {
        font-family: FZZYJW--GB1-0;
        font-weight: 0;
        font-size: 14px;
        color: #262626;
      }
    }
    .title-line {
      width: 1px;
      height: 12px;
      background: #e8e9ed;
      margin: 0 12px;
    }
    .tags {
      padding: 0 8px;
      height: 24px;
      background: #eb61171a;
      border-radius: 4px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      color: #eb6117;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 8px;
    }
    .title-text {
      line-height: 20px;
      font-family: PingFangSC-Medium;
      font-weight: 500;
      font-size: 14px;
      color: #262930;
    }
  }
  .header-btns {
    display: flex;
    align-items: center;
    .btn-line {
      width: 1px;
      height: 12px;
      background: #e8e9ed;
      margin: 0 16px;
    }
    .btns {
      display: flex;
      align-items: center;
      height: 20px;
      cursor: pointer;
      position: relative;
      .icons {
        width: 16px;
        height: 16px;
        margin-right: 4px;
      }
      .text {
        font-family: PingFangSC-Regular;
        font-weight: 400;
        font-size: 14px;
        color: #262930;
        &.num {
          font-family: DS-Digital;
          font-size: 16px;
        }
        &.blue {
          color: #2776ff;
        }
      }
      .flex {
        display: flex;
        align-items: center;
      }
      .show-more-box {
        position: absolute;
        left: 0;
        top: 45px;
        width: 156px;
        background: #ffffff;
        border: 1px solid #e6ebf1;
        box-shadow: 0 2px 20px 0 #0050cb14;
        border-radius: 8px;
        box-sizing: border-box;
        padding: 8px;

        .more-btns {
          display: flex;
          align-items: center;
          height: 40px;
        }
        .more-icons {
          width: 16px;
          height: 16px;
          margin-right: 4px;
        }
      }
    }
    .header-btn {
      padding: 0 14px;
      height: 30px;
      cursor: pointer;
      background: #2776ff;
      border-radius: 15px;
      font-family: PingFangSC-Regular;
      font-weight: 400;
      font-size: 14px;
      line-height: 30px;
      color: #ffffff;
    }
  }
}
.experiment-box {
  height: calc(100% - 51px);
  display: flex;
  align-items: center;
  justify-content: space-between;
  background: #fafafa;
  position: relative;
  .experiment-main {
    flex: 1;
    height: 100%;
    display: flex;
    position: relative;
    justify-content: space-between;
    .main-box {
      flex: 1;
      height: 100%;
      box-sizing: border-box;
      position: relative;
      overflow: hidden;
      .iframe-box {
        width: 100%;
        height: 100%;
        box-sizing: border-box;
        position: relative;
        z-index: 1;
        .click-box {
          position: absolute;
          border-radius: 50%;
          width: 30px;
          height: 30px;
          border: 8px solid #eb6117;
          transition: all 0.3s ease-in-out;
        }
        .iframe {
          width: 100%;
          height: 100%;
          box-sizing: border-box;
          border: 0;
        }
      }
      .report-tip {
        position: absolute;
        bottom: 12px;
        left: 12px;
        right: 12px;
        height: 100px;
        background: #2776ff;
        border-radius: 12px;
        display: flex;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        .tip-title {
          font-family: PingFangSC-Medium;
          font-weight: 500;
          font-size: 24px;
          color: #ffffff;
          line-height: 30px;
        }
        .tip-arrow {
          background: url(@/assets/icon-arrow-link.png) no-repeat center;
          width: 30px;
          height: 30px;
          margin-left: 8px;
        }
      }
    }
    .sider-box {
      width: 300px;
      height: 100%;
      background: #ffffff;
      .sider-table-box {
        height: 100%;
        width: 100%;
        .sider-tab {
          display: flex;
          align-items: flex-start;
          height: 40px;
          overflow: hidden;
          position: relative;
          background: #f2f3f5;
          .sider-prev {
            width: 40px;
            cursor: pointer;
            height: 40px;
            background: #ffffff url(@/assets/icon-prev.png) no-repeat center;
          }
          .sider-next {
            width: 40px;
            cursor: pointer;
            height: 40px;
            background: #ffffff url(@/assets/icon-next.png) no-repeat center;
          }
          .sider-tab-scroller {
            width: 100%;
            overflow-x: auto;
            white-space: nowrap;
            display: flex;
            height: 58px;
          }
          .tab-title {
            width: 130px;
            flex-shrink: 0;
            height: 40px;
            background: #f2f3f5;
            display: flex;
            align-items: center;
            justify-content: center;
            font-family: PingFangSC-Regular;
            font-weight: 400;
            font-size: 14px;
            color: #4e5569;
            cursor: pointer;
            &.cur {
              background: #ffffff;
              font-family: PingFangSC-Medium;
              font-weight: 500;
              font-size: 14px;
              color: #262626;
            }
          }
        }
        .sider-table {
          padding: 12px;
          height: calc(100% - 40px);
          box-sizing: border-box;
          overflow: hidden;

          font-family: PingFangSC-Regular;
          font-weight: 400;
          font-size: 12px;
          color: #262626;
          line-height: 16px;
          /deep/.grey-cell {
            background: #f2f3f5;
            color: #4e5569;
            font-family: PingFangSC-Regular;
            font-weight: 400;
            font-size: 12px;
            color: #262626;
            line-height: 16px;
            padding: 12px 8px;
          }
          /deep/.t-table td {
            padding: 8px 0 !important;
          }
        }
      }
    }
  }
}
</style>
